package com.fanrui.code.socket.netty.core;

import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import com.google.protobuf.MessageLite;

import io.netty.channel.Channel;

public abstract class Session{

	private long playerId;
	private Channel channel;

	public Session(long playerId, Channel channel) {
		super();
		this.playerId = playerId;
		this.channel = channel;
	}

	public long getPlayerId() {
		return playerId;
	}

	/**
	 * 发送服务器端推送消息
	 * 
	 * @param push
	 */
	public void send(MessageLite push) {
		if(this.channel != null){
			this.channel.writeAndFlush(push);
		}
	}

	

	@Override
	public String toString() {
		return "PlayerSession [playerId=" + playerId + ", channel=" + channel + "]";
	}

	/**
	 * 判断这个Sender的channel是不是同一个
	 * 
	 * @param channel
	 * @return
	 */
	public boolean isSameSocket(Channel channel) {
		return this.channel.compareTo(channel) == 0;
	}

	/**
	 * 判断这两个Sender是不是同一个Channel建立的
	 * 
	 * @param channel
	 * @return
	 */
	public boolean isSameSocket(Session sender) {
		return this.channel.compareTo(sender.channel) == 0;
	}

	//
	// session attribute
	//
	private ConcurrentMap<String, Object> attributes = new ConcurrentHashMap<String, Object>();

	public void setAttribute(String key, Object value) {
		this.attributes.put(key, value);
	}

	public Object getAttribute(String key) {
		return this.attributes.get(key);
	}

	public void removeAttribute(String key) {
		this.attributes.remove(key);
	}

	public boolean hasAttribute(String key) {
		return this.attributes.containsKey(key);
	}

	public Set<String> getAttributeNames() {
		return this.attributes.keySet();
	}

	//
	// event
	//
	/**
	 * Session 建立完成后调用
	 */
	public void afterCreate() {

	}

	/**
	 * Session 消失前调用
	 */
	public void beforeRemove() {

	}
}
